package com.icehand.qiniu.config;

import com.icehand.qiniu.enums.ZoneEnum;
import com.icehand.qiniu.manager.QiniuUploadManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

/**
 * @author icehand
 */
@Slf4j
public class QiniuConfiguration {
    @Autowired
    private QiniuConfig qiniuConfig;

    @ConditionalOnMissingBean(QiniuUploadManager.class)
    @Bean
    public QiniuUploadManager qiniuUploadManager() {
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        QiniuConfig.Bucket bucket = qiniuConfig.getBucket();
        UploadManager uploadManager = new UploadManager(new com.qiniu.storage.Configuration(ZoneEnum.choiceZoneByName(bucket.getZone())));
        String token = auth.uploadToken(bucket.getName());
        log.info("init QiniuUploadManager");
        return new QiniuUploadManager(uploadManager, token);
    }

}
